//
//  ViewController.m
//  TestCaptureWindow
//
//  Created by lbxia on 2022/3/21.
//

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
}

- (IBAction)start:(id)sender {
    
    NSLog(@"dd");
    
    
    NSMenu * menu = [[NSMenu alloc]init];
    NSArray * windows = (NSArray *)CFBridgingRelease(CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID));
    NSMutableDictionary *windowInfoDictionary = [NSMutableDictionary dictionary];
    for (NSDictionary * runApp in windows) {
        NSString* windowOwner = [runApp objectForKey:(NSString *)kCGWindowOwnerName];
        NSInteger onscreen = [[runApp objectForKey:(NSString *)kCGWindowIsOnscreen] integerValue];
        NSInteger windowID = [[runApp objectForKey:(NSString *)kCGWindowNumber] integerValue];
        NSString * windowName = [runApp objectForKey:(NSString *)kCGWindowName];
        NSString * windowPID = [NSString stringWithFormat:@"%@",[runApp objectForKey:(NSString *)kCGWindowOwnerPID]];
        CGRect bounds;
        CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)[runApp objectForKey:(NSString*)kCGWindowBounds], &bounds);
        
        if (onscreen == 1 && bounds.size.height != 22 && bounds.size.height != 46 && ![windowOwner isEqualToString:@"Dock"] && ![windowName isEqualToString:@"Dock"]) {
            [windowInfoDictionary setValue:runApp forKey:[NSString stringWithFormat:@"%ld",(long)windowID]];
            NSString * itemTitle;
            if (windowName.length > 0) {
                itemTitle = [windowOwner stringByAppendingFormat:@" - %@",windowName];
            }else{
                itemTitle = windowOwner;
            }
            NSMenuItem * item = [[NSMenuItem alloc]initWithTitle:itemTitle action:@selector(takeScreenshot:) keyEquivalent:@""];
            NSString * appPath = [NSString stringWithFormat:@"/Applications/%@.app",windowOwner];
            if (![[NSFileManager defaultManager] fileExistsAtPath:appPath]) {
//                NSString * taskString = [self luanchArguments:@[@"-A"] grepArguments:@[@"-w",windowPID]];
//                appPath = [@"/" stringByAppendingString:[[taskString componentsSeparatedByString:@"/Contents"].firstObject componentsSeparatedByString:@" /"].lastObject];
            }
            NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFile:appPath];
            [icon setSize:CGSizeMake(25, 25)];
            [item setImage:icon];
            item.tag = windowID;
            [menu addItem:item];
            
            NSLog(@"%@,%@",windowOwner,windowName);
        }
    }
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}


@end
